package com.suyafei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suyafei.enums.BizCodeEnum;
import com.suyafei.enums.SendCodeEnum;
import com.suyafei.feign.CouponFeignService;
import com.suyafei.interceptor.LoginIntercept;
import com.suyafei.mapper.UserMapper;
import com.suyafei.model.LoginUser;
import com.suyafei.model.UserDO;
import com.suyafei.request.NewUserCouponRequest;
import com.suyafei.request.UserLoginRequest;
import com.suyafei.request.UserRegisterRequest;
import com.suyafei.service.FileService;
import com.suyafei.service.NotifyService;
import com.suyafei.service.UserService;
import com.suyafei.util.CommonUtil;
import com.suyafei.util.JWTUtil;
import com.suyafei.util.JsonData;
import com.suyafei.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @program: suyafei-1024-shop
 * @description
 * @author: luffy
 * @create: 2021-02-25 21:57
 */
@Service
@Slf4j
public class UserServiceImpl  implements UserService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 上传用户头像
     *
     * 默认最大是1m，超过则报错
     * @param registerRequest
     * @return
     */
    @Override
    public JsonData register(UserRegisterRequest registerRequest) {

        boolean checkCode = false;
        if (StringUtils.isNotBlank(registerRequest.getMail())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER, registerRequest.getMail(), registerRequest.getCode());
        }
        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }

        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(registerRequest, userDO);

        userDO.setCreateTime(new Date());
        userDO.setSlogan("..................");
        //设置密码
        // 生成秘钥 盐
        userDO.setSecret("$1$"+ CommonUtil.getStringNumRandom(8));

        //密码加盐
        String cryptPwd = Md5Crypt.md5Crypt(registerRequest.getPwd().getBytes(), userDO.getSecret());
        userDO.setPwd(cryptPwd);
        //账号唯一性检查 TODO
        if (checkUnique(userDO.getMail())) {
            int rows = userMapper.insert(userDO);
            log.info("注册成功:{}rows:{}",userDO.toString(),rows);
            //新用户注册成功，初始化信息。 TODO
            userRegisterInitTask(userDO);
            return JsonData.buildSuccess();
        }else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT);
        }

    }

    /**
     * 用户登录
     *
     * 1.根据mail去找这个记录
     * 2.用秘钥+用户铭文，进行加密然后在和数据库密文进行匹配
     *
     * @param userLoginRequest
     * @return
     */
    @Override
    public JsonData login(UserLoginRequest userLoginRequest) {
        List<UserDO> userDOList = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail", userLoginRequest.getMail()));


        if (userDOList != null && userDOList.size() == 1) {
            //已经注册
            UserDO userDO = userDOList.get(0);
            String cryptPwd = Md5Crypt.md5Crypt(userLoginRequest.getPwd().getBytes(), userDO.getSecret());
            if (cryptPwd.equals(userDO.getPwd())) {

                //登录成功，生成token
                LoginUser loginUser = new LoginUser();
                BeanUtils.copyProperties(userDO, loginUser);
                String token = JWTUtil.geneJsonWebToken(loginUser);

                return JsonData.buildSuccess(token);
            }else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }
        }else{
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }

    /**
     * 查找用户详情
     * @return
     */
    @Override
    public UserVO findUserDetail() {
        LoginUser loginUser = LoginIntercept.threadLocal.get();

        UserDO userDO = userMapper.selectOne(new QueryWrapper<UserDO>().eq("id", loginUser.getId()));

        UserVO userVO = new UserVO();

        BeanUtils.copyProperties(userDO, userVO);

        return userVO;
    }

    /**
     *校验用户唯一性
     * @param mail
     * @return
     */
    private boolean checkUnique(String mail) {

        //TODO


        return true;
    }

    /**
     * 用户注册，初始化福利信息 TODO
     *
     * @param userDO
     */
    private void userRegisterInitTask(UserDO userDO) {
        NewUserCouponRequest request = new NewUserCouponRequest();
        request.setName(userDO.getName());
        request.setUserId(userDO.getId());
        JsonData jsonData = couponFeignService.addNewUserCoupon(request);
        log.info("发送新用户注册优惠券{},结果{}",request.toString(),jsonData.toString());
    }
}
